package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.pojo.UserDTO;
import com.itheima.pojo.UserLoginVo;
import com.itheima.pojo.UserPage;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private  final UserMapper userMapper;
    @Override
    public UserPage<User> list(UserDTO userDTO) {
        //1调用mapper查询总数
        int total = userMapper.list(userDTO);
        //2调用mapper分页查询
         List<User> userList = userMapper.page(userDTO);
         return new UserPage<>(total,userList);
    }

    @Override
    public UserLoginVo login(User user) {
         User userInfo = userMapper.login(user);
         if(userInfo!=null){
             UserLoginVo vo =new UserLoginVo();
             //把第一个参数属性值，复制给第二个参数
             BeanUtils.copyProperties(userInfo,vo);
             //生成token令牌
             Map<String,Object> payload = new HashMap<>();
             payload.put("id",userInfo.getId());
             payload.put("username",userInfo.getUsername());
             payload.put("name",userInfo.getName());
             String token = JwtUtils.generateJwt(payload);
             vo.setToken(token);
             return vo;
         }
        return null;
    }


}
